/**
 * 文件管理弹框
 * @Author: zhangshubin
 * @Date: 2023-12-20 09:14:58
 * @Last Modified by: zhangshubin
 * @Last Modified time: 2023-12-22 17:53:01
 *
 */
import { Button, Card, Col, Image, Input, Row, Upload, UploadProps, message } from 'antd'
import DraggableDialog from '../DraggableDialog'
import { useEffect, useState } from 'react'

import './index.less'

import * as FileApi from '@/api/file'

interface IImageLibraryDialogProps {
  onClose?: () => void
  onOk?: (url: string) => void
}

interface IImageData {
  name: string
  path: string
  url: string
  id: number
}
const LIB_PREFIX = 'PANGU_IMG_LIB_'

export default function ImageLibraryDialog(props: IImageLibraryDialogProps) {
  // 图像列表
  const [images, setImages] = useState<IImageData[]>([])
  // 当前选中的图片key
  const [selectImgId, setSelectImgId] = useState<number>(0)
  // 文件名
  const [fileName, setFileName] = useState('')

  // 上传配置
  const uploadProps: UploadProps = {
    accept: 'image/*',
    action: import.meta.env.VITE_UPLOAD_URL,
    beforeUpload: (file) => {
      // 读取上传文件
      const isImg =
        file.type === 'image/png' || file.type == 'image/jpeg' || file.type == 'image/webp'
      if (!isImg) {
        message.error(`${file.name} 不是正确的图片格式`)
        return Upload.LIST_IGNORE
      }
      file
        .arrayBuffer()
        .then((data) => {
          return FileApi.uploadImage(data, {
            name: LIB_PREFIX + file.name
          })
        })
        .then((data) => {
          // 上传成功后，刷新界面
          queryImages()
        })
      return Upload.LIST_IGNORE
    }
  }

  const onSave = () => {
    const img = images.find((n) => n.id == selectImgId)
    if (img) {
      props.onOk && props.onOk(img.url)
    }
  }

  /**
   * 查询图库
   */
  const queryImages = async () => {
    const data = await FileApi.getFilePage({
      path: LIB_PREFIX + fileName,
      type: 'image'
    })
    setImages(data.list)
  }

  const formatFileName = (name: string) => {
    const n = name.replace(LIB_PREFIX, '')
    return n.split('.')[0]
  }

  // 打开时默认查询
  useEffect(() => {
    queryImages()
  }, [])

  return (
    <DraggableDialog
      title="图片库"
      open={true}
      onCancel={props.onClose}
      className="img-libs-dialog "
      width={450}
      footer={[
        <Button
          key="cancle"
          size="small"
          className="font-size-12px! mr-20px"
          onClick={(e) => props.onClose && props.onClose()}
        >
          取消
        </Button>,
        <Button
          type="primary"
          key="ok"
          size="small"
          className="font-size-12px!"
          onClick={(e) => onSave()}
        >
          确定
        </Button>
      ]}
    >
      <Row className="w-100%">
        <Col span={12}>
          <Input
            className="h-26px font-size-12px"
            allowClear
            placeholder="请输入文件名"
            onChange={(e) => {
              setFileName(e.target.value)
            }}
          />
        </Col>

        <Col span={12} className="flex flex-justify-end flex-items-center">
          <Button
            type="primary"
            size="small"
            className="font-size-12px! "
            onClick={() => queryImages()}
          >
            查询
          </Button>
          <Upload {...uploadProps}>
            <Button size="small" className="font-size-12px! ml-10px">
              上传新图片
            </Button>
          </Upload>
        </Col>
      </Row>

      <Row className="mt-20px">
        <Col span={24}>
          <Card>
            {images.map((n) => {
              return (
                <Card.Grid
                  key={n.id}
                  className={`p-5px! w-80px! h-100px cursor-pointer  ${
                    selectImgId == n.id && 'selected'
                  }`}
                  onClick={() => {
                    setSelectImgId(n.id)
                  }}
                >
                  <div className="h-70px text-center">
                    <Image
                      preview={false}
                      src={n.url}
                      className="object-contain max-h-70px! max-w-70px!"
                    />
                  </div>
                  <div className="font-size-12px text-center ">{formatFileName(n.path)}</div>
                </Card.Grid>
              )
            })}
          </Card>
        </Col>
      </Row>
    </DraggableDialog>
  )
}
